<template>
  <div>
    <el-row style="height:260px">
      <el-col :span="16">
        <el-card v-loading="listLoading" style="margin:5px;height:250px">
          <el-descriptions :title="inviteInfo.title">
            <el-descriptions-item label="项目号" :span="1">
              <el-tag size="small">{{ inviteInfo.projectSerial }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="项目名" :span="2">
              <el-tag size="small">{{ inviteInfo.projectName }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="阶段" :span="1">
              <el-tag type="warning" size="small">{{ getInviteProgressString(inviteInfo.progress) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="当前轮次" :span="2">
              <el-tag type="warning" size="small">{{ inviteInfo.round }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注">{{ inviteInfo.summary }}</el-descriptions-item>
          </el-descriptions>
          <!-- <h2>{{inviteInfo.title}}</h2>
            <h3>{{inviteInfo.projectSerial}}-{{inviteInfo.projectName}}</h3>
            <h3>{{getInviteProgressString(inviteInfo.progress)}}</h3>
            <h3>阶段:{{inviteInfo.round}}</h3>
          <h4>{{inviteInfo.summary}}</h4>-->
          <el-button v-show="!(isClickShow && inviteInfo.supplyGroup === '项目经理')" v-permission="'InviteDetail-remind'" type="primary" @click="progressClick(inviteInfo.supplyGroup)">提醒</el-button>
          <!-- <el-button v-show="inviteInfo.progress === 1 && !inviteInfo.remindSupplierFlag" v-permission="'InviteDetail-remind'" type="primary" @click="progressClick">提醒</el-button> -->
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card v-loading="listLoading" style="margin:5px;height:250px">
          <el-row>
            <!-- <el-button style="margin:5px;">上传文件</el-button> -->
            <el-upload v-show="false" :on-success="onsuccess" class="upload-demo" :action="actionData">
              <el-button v-show="false" ref="upload1" class="btnUpload" />
            </el-upload>
            <el-button
              v-show="!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
              v-permission="'InviteDetail-Uploadfiles'"
              type="primary"
              size="medium"
              style="margin-left:10px"
              plain
              @click="importDoc"
            >上传文件</el-button>
          </el-row>
          <el-table ref="filesTable" :data="inviteInfo.files" :row-style="{height:'40px'}" :cell-style="{padding:'0px'}" :show-header="false" height="155px" style="width: 100%;">
            <el-table-column prop="fileName" label="fileName">
              <template slot-scope="scope">
                <el-button icon="el-icon-paperclip" type="text" @click="downLoadClick(scope.row)">{{ scope.row.fileName }}</el-button>
                <div />
              </template>
            </el-table-column>
            <el-table-column width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  v-show="!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
                  v-permission="'InviteDetail-deletefiles'"
                  type="text"
                  size="small"
                  style="color:orangered;"
                  @click="deletefilesClick(scope.row)"
                >{{ $t('button.Delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <AddBidDialog :add-bid-dialog-flag.sync="addBidDialogFlag" :invite-info="inviteInfo" @updateValue="updateValue" />
    <FinalSubmit :final-submit-dialog.sync="finalSubmitDialog" :invite-info="inviteInfo" @updateValue="updateValue" />
    <EditBidDialog :edit-bid-dialog-flag.sync="editBidDialogFlag" :edit-bid-data="editBidData" @updateValue="updateValue" />
    <el-card style="margin:5px;height:550px">
      <el-button v-show="inviteInfo.progress < 3 " v-permission="'InviteDetail-AddBid'" style="margin-top:10px" type="success" plain @click="AddBidClick">投标</el-button>
      <el-button
        v-show="inviteInfo.progress === 4 && !(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        v-permission="'InviteDetail-FinalSubmit'"
        style="margin-top:10px"
        type="success"
        plain
        @click="FinalSubmitClick"
      >最终报价</el-button>
      <el-button
        v-show="inviteInfo.progress < 3 &&!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        v-permission="'InviteDetail-nextRound'"
        style="margin-top:10px"
        type="primary"
        plain
        @click="nextRoundClick"
      >进入下一轮</el-button>
      <el-button
        v-show="inviteInfo.progress === 3 &&!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        v-permission="'InviteDetail-ConfirmBid'"
        style="margin-top:10px"
        type="primary"
        plain
        @click="ConfirmBidClick"
      >确认中标</el-button>
      <el-button
        v-show="(inviteInfo.progress === 3 || inviteInfo.progress === 4) &&!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        v-permission="'InviteDetail-GobackLastGround'"
        style="margin-top:10px"
        type="primary"
        plain
        @click="GobackLastGroundClick"
      >退回招标</el-button>
      <el-button
        v-show="inviteInfo.progress < 3 &&!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        v-permission="'InviteDetail-Negotiation'"
        style="margin-top:10px"
        type="warning"
        plain
        @click="NegotiationClick"
      >议标</el-button>
      <el-button
        v-show="isEndMethod && inviteInfo.progress === 4 &&!(isClickShow && inviteInfo.supplyGroup === '项目经理')"
        style="margin-top:10px"
        type="warning"
        plain
        @click="EndMethodClick"
      >结束中标</el-button>
      <!-- <el-button style="margin-top:10px" type="primary" plain @click="EndMethodClick">添加供应商</el-button> -->
      <el-table
        ref="bidsTable"
        v-loading="listLoading"
        :data="inviteInfo.bids"
        border
        height="450px"
        :row-style="{height:'40px'}"
        :cell-style="{padding:'0px'}"
        :row-class-name="tableRowClassName"
        style="width: 100%;  margin-top: 10px;"
      >
        <el-table-column v-if="buttons.indexOf('InviteDetail-operation')>-1" type="selection" width="50" align="center" />
        <!-- <el-table-column v-if="buttons.indexOf('InviteDetail-operation')>-1" width="100" align="center">
          <template slot-scope="scope">
            <template v-if="inviteInfo.round === scope.row.currentRound">
              <el-button
                type="text"
                size="small"
                @click="editbidsClick(scope.row)"
              >{{ $t('button.Edit') }}</el-button>
              <el-button
                type="text"
                size="small"
                @click="deletebidsClick(scope.row)"
              >{{ $t('button.Delete') }}</el-button>
            </template>
            <span v-else>--------------</span>
          </template>
        </el-table-column> -->
        <el-table-column v-if="buttons.indexOf('InviteDetail-isNextRound')>-1" label="是否进入下一轮" align="center" width="140">
          <template slot-scope="scope">
            <el-switch v-if="inviteInfo.round === scope.row.currentRound" v-model="scope.row.isNextRound" active-text="开" inactive-text="关" @change="isNextRoundChange(scope.row)" />
            <span v-else>------------</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商名" align="center" />
        <el-table-column prop="remark" label="投标说明" align="center" />
        <el-table-column prop="total" label="总价（含税）" align="center" />
        <el-table-column prop="currentRound" label="轮次" align="center">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.currentRound }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="附件" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.files.length === 1" type="text" size="small" @click="downLoadClick(scope.row.files[0])">{{ scope.row.files[0].fileName }}</el-button>
            <el-button v-else type="text" size="small" @click="ParticularsClick(scope.row)">详情</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="inviteId" label="inviteId" align="center" /> -->
        <!-- <el-table-column prop="bidResult" label="bidResult" align="center">
            <template slot-scope="scope">
              {{ scope.row.bidResult?'启用':"禁用" }}
            </template>
        </el-table-column>-->
      </el-table>
    </el-card>
    <el-dialog title="附件" :visible.sync="ParticularsDialog" width="500px">
      <el-table ref="filesTable" :data="ParticularsData" :row-style="{height:'40px'}" :cell-style="{padding:'0px'}" :show-header="false" height="155px" style="width: 100%;">
        <el-table-column prop="fileName" label="fileName">
          <template slot-scope="scope">
            <el-button icon="el-icon-paperclip" type="text" @click="downLoadClick(scope.row)">{{ scope.row.fileName }}</el-button>
            <div />
          </template>
        </el-table-column>
        <!-- <el-table-column width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              style="color:orangered;"
              @click="deletefilesClick(scope.row)"
            >{{ $t('button.Delete') }}</el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </el-dialog>

    <!-- 提醒 -->
    <el-dialog :visible.sync="SupplierListDialog" width="650px">
      <el-form v-model="SupplierData" label-width="120px" size="large">
        <el-row>
          <el-col :span="17">
            <el-form-item label="companyName">
              <el-input v-model.trim="SupplierData.companyName" placeholder="companyName" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-button type="primary" plain @click="SupplierClick">搜索</el-button>
            <el-button @click="SupplierReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table ref="SupplierList" :data="SupplierList" :row-style="{height:'40px'}" :cell-style="{padding:'0px'}" height="400px" style="width: 100%;">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="companyName" label="companyName" />
        <el-table-column prop="email" label="email" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="SupplierSubmit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  DeleteFileInfo,
  SendInviteMail,
  getSupplier,
  IntoNextRound,
  IntoNext,
  CancelNext,
  AddFile,
  InviteGet,
  GetFileById,
  UpdateBid,
  DeleteBid,
  PublishBid,
  InvitePagion,
  Negotiation,
  GobackLastGround,
  EndMethod,
  ConfirmBid
} from '@/api/SRM'
import { localgettoken } from '@/utils/auth'
import { Message } from 'element-ui'
import Bid from './components/Bid.vue'
import AddBidDialog from './components/AddBidDialog.vue'
import FinalSubmit from './components/FinalSubmit.vue'
import EditBidDialog from './components/EditBidDialog.vue'
import config from '@/config'
import permission from '@/permission/index.js' // 权限判断指令
import { getInviteProgressString } from '@/filters/index.js'
import { QueryModelItem, QueryModelBuilder } from '@/utils/vuage.js'
export default {
  name: 'InviteDetail',
  directives: { permission },
  components: { AddBidDialog, EditBidDialog, FinalSubmit },
  data() {
    return {
      inviteId: 0,
      inviteInfo: {},
      tableData: [],
      bids: [],
      listLoading: false,
      addBidDialogFlag: false,
      editBidDialogFlag: false,
      finalSubmitDialog: false,
      // 上传地址
      actionData: `http://${document.location.hostname}:${document.location.port}/File/Upload`,
      buttons: JSON.parse(sessionStorage.getItem('buttons')) || [],
      // 详情弹窗
      ParticularsDialog: false,
      ParticularsData: [],
      // 招标弹窗及数据
      editBidDialog: false,
      editBidData: {
        id: 0,
        supplierName: '',
        remark: '',
        total: 0,
        dueCycle: 0,
        inviteId: 0
      },
      //
      isEndMethod: false,
      // 提醒dialog
      SupplierListDialog: false,
      SupplierData: {
        companyName: ''
      },
      SupplierList: [],
      token: JSON.parse(localgettoken()),
      isClickShow: false
    }
  },

  mounted() {
    // 是 超级管理员 return
    // 不是 超级管理员  分组是不是项目经理

    console.log(this.token, this.inviteInfo)
    console.log(this.token.roles[0].roleName === '超级管理员')
    if (this.token.roles[0].roleName === '工事项目经理') {
      this.isClickShow = true
    }
  },
  created() {
    this.inviteId = this.$route.query.id
    this.queryData()
  },
  methods: {
    /** 获取页面数据*/
    async queryData() {
      try {
        this.listLoading = true
        const res = await InviteGet({ id: this.inviteId })
        this.inviteInfo = res.data.data
        console.log(this.inviteInfo, 'inviteInfo')
        this.bids = this.inviteInfo.bids
        const a = this.bids.find((item) => item.isFinalBid)
        if (a === undefined) {
          this.isEndMethod = false
        } else {
          this.isEndMethod = true
        }
        // console.log(this.isEndMethod)
      } catch (error) {
        Message.error('获取数据失败')
      } finally {
        this.listLoading = false
      }
    },
    updateValue() {
      this.queryData()
    },
    // 上传
    async onsuccess(response, file, fileList) {
      console.log(response, file, fileList, 'response, file, fileList')
      // this.AddInviteData.files.push(response.data)
      await AddFile({
        inviteId: this.inviteInfo.id,
        fileId: response.data.id
      })
      Message.success('上传成功')
      this.queryData()
    },
    // 判断是否勾选文件
    importDoc() {
      this.$refs['upload1'].$el.click() // 打开上传文件弹窗
    },
    // 删除当前文件
    deletefilesClick(data) {
      this.$confirm('确认删除当前文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          console.log(this.inviteInfo, this.inviteInfo, data, 'inviteInfo')
          await DeleteFileInfo({
            inviteId: this.inviteInfo.id,
            fileId: data.id
          })
          Message.success('操作成功')
          this.queryData()
        })
        .catch(() => {})
    },
    getInviteProgressString(data) {
      return getInviteProgressString(data)
    },
    // 详情
    ParticularsClick(data) {
      console.log(data)
      this.ParticularsData = data.files
      this.ParticularsDialog = true
    },
    /** 下载文件 */
    async downLoadClick(data) {
      console.log(`${baseURL}File/Download?id=${data.id}`, '11111111111111111')
      console.log(config.baseUrl.dev, 'config.baseUrl.dev')
      console.log(config.baseUrl.build, 'config.baseUrl.build')
      let baseURL
      if (process.env.NODE_ENV === 'development') {
        baseURL = config.baseUrl.dev
        window.open(`${baseURL}File/Download?id=${data.id}`)
      } else {
        baseURL = config.baseUrl.build
        window.open(`${baseURL}/File/Download?id=${data.id}`)
      }
    },
    /** 新增投标Dialog */
    AddBidClick() {
      this.addBidDialogFlag = true
      console.log(this.inviteInfo, this.addBidDialogFlag)
    },
    // 最终报价
    FinalSubmitClick() {
      this.finalSubmitDialog = true
    },
    //
    async isNextRoundChange(data) {
      console.log(data)
      if (data.isNextRound) {
        await IntoNext({ id: data.id })
        Message.success('操作成功')
      } else {
        await CancelNext({ id: data.id })
        Message.success('操作成功')
      }
    },
    // 进入下一轮
    async nextRoundClick() {
      console.log(this.inviteInfo, 'inviteInfo.bids')
      const NextRound = this.inviteInfo.bids.find((item) => item.isNextRound)
      console.log(NextRound, 'NextRound')
      if (NextRound) {
        await IntoNextRound({ id: this.inviteInfo.id })
        Message.success('操作成功')
        this.queryData()
      }
    },
    // 提醒搜索框
    async SupplierClick() {
      // console.log(this.inviteInfo.supplyGroup, "asdsad", this.SupplierData);
      const res = await getSupplier({
        supplyGroup: this.inviteInfo.supplyGroup,
        companyName: this.SupplierData.companyName,
        size: 1000
      })
      this.SupplierList = res.data.data
    },
    // 提醒的重置
    async SupplierReset() {
      this.SupplierData.companyName = ''
    },
    // 提醒
    async progressClick(data) {
      const res = await getSupplier({ supplyGroup: data, size: 1000 })
      this.SupplierList = res.data.data
      this.SupplierListDialog = true
    },
    // 提醒确认
    async SupplierSubmit() {
      // console.log(this.$refs.SupplierList.selection)
      const arr = []
      this.$refs.SupplierList.selection.forEach((item) => {
        arr.push(item.email)
      })
      console.log(arr)
      await SendInviteMail({ id: this.inviteInfo.id, names: arr })
      Message.success('操作成功')
      this.queryData()
    },
    // 招标修改
    editbidsClick(data) {
      console.log(data)
      this.editBidData.id = data.id
      this.editBidData.supplierName = data.supplierName
      this.editBidData.remark = data.remark
      this.editBidData.total = data.total
      this.editBidData.dueCycle = data.dueCycle
      this.editBidData.inviteId = data.inviteId
      this.editBidDialogFlag = true
    },
    /** 招标删除 */
    deletebidsClick(data) {
      this.$confirm('确认删除当前Bid吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await DeleteBid({ id: data.id })
          this.queryData()
          Message.success('操作成功')
        })
        .catch(() => {})
    },
    //
    async NegotiationClick() {
      if (this.$refs.bidsTable.selection.length > 1) { return Message.warning('只能勾选一条数据') }
      if (this.$refs.bidsTable.selection.length === 0) { return Message.warning('请选择数据') }
      // console.log({
      //   'id': this.inviteId,
      //   'bidId': this.$refs.bidsTable.selection[0].id
      // })
      await Negotiation({
        id: this.inviteId,
        bidId: this.$refs.bidsTable.selection[0].id
      })
      Message.success('操作成功')
      this.queryData()
    },
    // 确认中标
    async ConfirmBidClick() {
      // if (this.$refs.bidsTable.selection.length > 1) return Message.warning('只能勾选一条数据')
      // if (this.$refs.bidsTable.selection.length === 0) return Message.warning('请选择数据')
      await ConfirmBid({
        id: this.inviteId
      })
      Message.success('操作成功')
      this.queryData()
    },
    // 退回招标
    async GobackLastGroundClick(data) {
      await GobackLastGround({
        id: this.inviteId
      })
      Message.success('操作成功')
      this.queryData()
    },
    //
    async EndMethodClick() {
      await EndMethod({ id: this.inviteId })
      Message.success('操作成功')
      this.queryData()
    },
    /** 打开招标详情界面 */
    detailsClick(data) {
      console.log(data)
      // this.$router.push({
      //   name: 'InviteDetail',
      //   query: { id: data.id }
      // })
      this.inviteId = data.id
      this.queryData()
    },
    // 改变row的背景
    tableRowClassName({ row, rowIndex }) {
      // console.log(row.isTimeout,rowIndex);
      if (row.isFinalBid) {
        return 'isFinalBid'
      } else if (row.bidResult) {
        return 'success-row'
      }
      return ''
    }
  }
}
</script>

<style>
.el-table .success-row {
  background: goldenrod;
}
.el-table .isFinalBid {
  background: gold;
}
</style>
